package com.redwine.app.utils;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;

import com.redwine.app.R;
import com.redwine.app.view.RoundProgressBar;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import static android.os.Looper.getMainLooper;
import static com.redwine.app.utils.FileUtils.getSDPath;

/**
 * 作者：gassion on 17/6/25 08:05
 * 最可怕的敌人，就是没有坚强的信念。
 */

public class DownLoadUtils {

    private int downLoadFileSize;
    private int fileSize;
    private final String TAG = "DownLoadUtils";
    private Context mContext;
    private DownListener downListener;
    private RoundProgressBar process;


    public DownLoadUtils(Context context, DownListener downListener) {
        this.mContext = context;
        this.downListener = downListener;
    }

    /**
     * 文件下载
     *
     * @param url：文件的下载地址
     * @throws IOException
     */
    public void down_file(String url, String name) throws IOException {
        //获取文件名
        URL myURL = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) myURL.openConnection();
        conn.connect();
        InputStream is = conn.getInputStream();
        fileSize = conn.getContentLength();//根据响应获取文件大小
        if (is == null) throw new RuntimeException("stream is null");
        File file1 = new File(getSDPath());
        File file2 = new File(getSDPath() + name);
        if (!file1.exists()) {
            file1.mkdirs();
        }
        if (!file2.exists()) {
            file2.createNewFile();
        }
        FileOutputStream fos = new FileOutputStream(getSDPath() + name);
        //把数据存入路径+文件名
        byte buf[] = new byte[1024];
        downLoadFileSize = 0;
        sendMsg(0);
        do {
            //循环读取
            int numread = is.read(buf);
            if (numread == -1) {
                break;
            }
            fos.write(buf, 0, numread);
            downLoadFileSize += numread;

            sendMsg(1);//更新进度条
        } while (true);

        sendMsg(2);//通知下载完成

        try {
            is.close();
        } catch (Exception ex) {
            sendMsg(3);
        }

    }

    public ProgressDialog mProgressDialog;

    private ProgressDialog loadingDialog() {
        LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.loading_download_dialog, null);// 得到加载view
        LinearLayout layout = (LinearLayout) v.findViewById(R.id.dialog_view);// 加载布局
        process = (RoundProgressBar) v.findViewById(R.id.progress);
        process.setMax(100);
        mProgressDialog = new ProgressDialog(mContext, R.style.loading_dialog_style);
        mProgressDialog.show();
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.setCancelable(false);
        mProgressDialog.setContentView(layout, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));// 设置布局
        mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {

            }
        });
        return mProgressDialog;
    }

    private void dismiss() {
        if (null != mProgressDialog) mProgressDialog.dismiss();
    }

    private void sendMsg(int flag) {
        Message msg = new Message();
        msg.what = flag;
        handler.sendMessage(msg);
    }

    Handler handler = new Handler(getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {//定义一个Handler，用于处理下载线程与UI间通讯
            if (!Thread.currentThread().isInterrupted()) {
                switch (msg.what) {
                    case 0:
                        loadingDialog();
                        break;

                    case 1:
                        int result = downLoadFileSize * 100 / fileSize;
                        Log.e("size",result+"====="+fileSize);
                        process.setProgress(result);
                        break;
                    case 2:
                        if (null != downListener)
                            downListener.isSuccess(true);
                        dismiss();
                        break;

                    case 3:
                        if (null != downListener)
                            downListener.isSuccess(false);
                        dismiss();
                        break;
                }
            }
            super.handleMessage(msg);
        }
    };

    public interface DownListener {
        void isSuccess(boolean success);
    }
}
